<?php
// +---------------------------------------------------
// | 导出模型数据表结构、删除数据表SQL语句
// +---------------------------------------------------
// | Author: liang 辰风沐阳 23426945@qq.com
// +---------------------------------------------------

declare(strict_types=1);

namespace command;

use think\facade\Db;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;

class Table extends Command
{
    /**
     * 指令配置
     */
    protected function configure()
    {
        $this->setName('make:table')
            ->addArgument('name', Argument::OPTIONAL, "your name")
            ->setDescription('table sql write file');
    }

    /**
     * 执行指令
     *
     * @param Input $input
     * @param Output $output
     */
    protected function execute(Input $input, Output $output)
    {
        $name = trim($input->getArgument('name'));
        $name = $name ?: 'thinkphp';

        // 导出数据表结构、删除数据表语句
        $storage = $this->export($name);
        $array = [
            "～～～～～～ 欢迎使用微擎小程序TP6.0框架 ～～～～～～",
            "Author: liang 辰风沐阳 23426945@qq.com",
            "PHP技术群: 159789818 ThinkPHP技术群: 828567087 (QQ群)",
            "模块标识: {$name} 数据表结构SQL语句已导入文件 " . date('Y-m-d H:i:s'),
            "SQL文件存放目录: {$storage}",
        ];
        $content = '';
        foreach ($array as $value) $content .= "\n{$value}\n";
        // 指令输出
        $output->writeln($content);
    }

    // +---------------------------------------------------
    // | 导出数据表结构、删除数据表SQL语句
    // +---------------------------------------------------

    /**
     * 将模块数据表结构导入文件
     */
    private function export($name)
    {
        $time = date('dHis');
        $key = 'Tables_in_' . $name;
        $tables = array_column(Db::query('show tables'), $key);
        $install = '';
        $uninstall = '';
        foreach ($tables as $value) {
            $show = Db::query("show create table `{$value}`");
            $install .= $this->change($show[0]['Create Table']);
            $uninstall .= "DROP TABLE IF EXISTS `{$value}`;" . PHP_EOL;
        }
        $storage = runtime_path() . 'table';
        file_exists($storage) || mkdir($storage, 0777, true);
        file_put_contents($storage . "/{$time}_install.sql", rtrim($install));
        file_put_contents($storage . "/{$time}_uninstall.sql", rtrim($uninstall));
        return $storage;
    }

    /**
     * 建表语句格式转换
     *
     * @param string $sql
     */
    private function change(string $sql)
    {
        $sql = preg_replace('/AUTO_INCREMENT=(\d+)\s{1}/', '', $sql);
        return str_replace('CREATE TABLE `', 'CREATE TABLE IF NOT EXISTS `', $sql) . ';' . PHP_EOL . PHP_EOL;
    }
}
